package com.tensquare.manager.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import io.jsonwebtoken.Claims;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import util.JwtUtil;

/**
 * 后台网关过滤器.
 *
 * @author 宫新程
 * @since 2019/3/22 1:47
 */
@Slf4j
@Component
public class ManagerFilter extends ZuulFilter {

  @Resource private JwtUtil jwtUtil;

  /** 过滤器类型（请求前/后执行）. return "pre"：执行前过滤 return "post"：执行之后 */
  @Override
  public String filterType() {
    return "pre";
  }

  /** 多个过滤器执行顺序：0：优先. 越小 优先级越高. */
  @Override
  public int filterOrder() {
    return 0;
  }

  /** 当前过滤器是否开启：true:开启，false：未开启. */
  @Override
  public boolean shouldFilter() {
    return true;
  }

  /** 执行的操作. return 任何Object的值都表示继续执行. setSendZuulResponse(false): 表示不再继续执行 */
  @Override
  public Object run() throws ZuulException {
    System.out.println("经过后台过滤器");
    RequestContext requestContext = RequestContext.getCurrentContext();
    HttpServletRequest request = requestContext.getRequest();

    // 注意！放行方法为 “OPTIONS”
    if (request.getMethod().equals("OPTIONS")) {
      return null;
    }
    // 登录请求放行
    if (request.getRequestURL().indexOf("login") > 0) {
      return null;
    }

    String header = request.getHeader("Authorization");
    // Authorization 不为空
    if (StringUtils.isNotBlank(header)) {
      if (header.startsWith("Bearer ")) {
        String token = header.replace("Bearer ", "");
        try {
          Claims claims = jwtUtil.parseJWT(token);
          String roles = (String) claims.get("roles");
          if ("admin".equals(roles)) {
            // 转发头信息
            requestContext.addZuulRequestHeader("Authorization", header);
            return null;
          }
        } catch (Exception e) {
          log.error("token解析失败，token: {}", token);
          e.printStackTrace();
        }
      }
    }
    requestContext.setSendZuulResponse(false);
    requestContext.setResponseStatusCode(403);
    requestContext.setResponseBody("权限不足");
    requestContext.getResponse().setContentType("text/html;charset=utf-8");
    return null;
  }
}
